﻿<%@ Page Language="C#" Debug="true" %> <%--AutoEventWireup="true" CodeBehind="SelectSignatureV3.aspx.cs" Inherits="adolsignweb.SelectSignatureV3" %>--%>

<%@ Assembly Name="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"  %>

<%@ Import Namespace="System.DirectoryServices" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server" type="text/C#">

    protected void Page_Init(object sender, EventArgs e)
    {
        //ViewState.Clear();
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewState.Clear();
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        string defaultNamingContext;
        using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"))
        {
            defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString();
        }

        string path = "LDAP://CN=Users," + defaultNamingContext;
        using (DirectoryEntry root = new DirectoryEntry(path))//, "xx\\xxxx", "xxxx"))
        {
            SearchResult result = GetCurrentActiveDirectoryUser(root);

            StringBuilder userInfo = new StringBuilder();
            userInfo.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");
            userInfo.AppendLine("var userinfovalues = new Array();");
            string result_content = "";
            if(result != null)
                foreach (string myKey in result.Properties.PropertyNames)
                {
                    string tab = "    ";
                    //Console.WriteLine(myKey + " = ");
                    result_content += myKey + " = ";// +"<br/>";//Environment.NewLine;
                    foreach (Object myCollection in result.Properties[myKey])
                    {
                        //Console.WriteLine(tab + myCollection);
                        result_content += tab + myCollection + "<br/>";//Environment.NewLine;
                        userInfo.AppendLine(String.Format("userinfovalues['{0}'] = '{1}';", myKey, myCollection.ToString()));
                    }//end foreach
                } //end foreach
            userInfo.AppendLine("</"+"script>");

            //AdUserInfo.InnerHtml = result_content;

            Page.ClientScript.RegisterStartupScript(this.GetType(), "userinfoobject", userInfo.ToString());// "var userinfovalues = new Array();");
        }

        ViewState.Clear();
    }

    SearchResult GetCurrentActiveDirectoryUser(DirectoryEntry root)
    {
        DirectorySearcher ds = new DirectorySearcher(root);
        System.Security.Principal.WindowsIdentity winIdent = System.Security.Principal.WindowsIdentity.GetCurrent();
        string userName = winIdent.Name;
        UserName.InnerText = userName;
        int hasDomain = userName.IndexOf(@"\");
        if (hasDomain > 0)
        {
            userName = userName.Remove(0, hasDomain + 1);
        }

        //string userFilter = "(&(objectCategory=user)(sAMAccountName={0}))";
        string userFilter = "(&(objectClass=user)(sAMAccountName={0}))";

        ds.SearchScope = SearchScope.Subtree;
        //ds.PropertiesToLoad.Add("distinguishedName");
        //ds.PageSize = 1;
        //ds.ServerPageTimeLimit = TimeSpan.FromSeconds(2);
        ds.Filter = string.Format(userFilter, userName);

        SearchResult sr = ds.FindOne();
        // now do something with sr.Properties["distinguishedName"][0]        

        ds.Dispose();
        return sr;
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <title>Outlook signature selecting (V3)</title>
</head>

<body style="margin: 20px">
    <form id="form1" runat="server">
    <div id="UserName" runat="server"></div>
    <%--<div onclick="ShowHideAdUserInfo();" style="cursor: pointer">(Show/hide user info)</div>--%>
    <%--<div id="AdUserInfo" runat="server" style="visibility: collapse"></div>--%>
    </form>

    <div style="margin-top: 10px; margin-bottom: 10px; padding: 5px; border: thin solid #C0C0C0; visibility: collapse;">
    Subfolder
    <select id="selectFolder" onchange="Scan();">
    </select>
    </div>

    <div id="outFrames"></div>
</body>

<script src="SelectSignatureV3Initialize.js" language="javascript" type="text/javascript"></script>

<script type="text/javascript" language="javascript">

    function ShowHideAdUserInfo() {
        var divAdUserInfo = document.getElementById('AdUserInfo');
        switch (divAdUserInfo.style.visibility) {
            case 'collapse':
                divAdUserInfo.style.visibility = 'visible';
                break;
            case 'visible':
                divAdUserInfo.style.visibility = 'collapse';
                break;
        }
    }

    function FindFile(FOo) {

        var FSo = new Enumerator(FOo.Files);

        var htmTabName = "htmTab1";
        var rtfTabName = "rtfTab1";
        var txtTabName = "txtTab1";
        var frameBox = "frameBox1";

        var listFiles = [];

        for (i = 0; !FSo.atEnd(); FSo.moveNext()) {
            if (FileName == "*" || FSo.item().name.slice(0, FSo.item().name.lastIndexOf(".")).toLowerCase().indexOf(FileName) > -1)
                if (Extention == "*" || FSo.item().name.slice(FSo.item().name.lastIndexOf(".") + 1).toLowerCase().indexOf(Extention) > -1) {
                    StrOut += "<tr " + ((i % 2) ? "" : "bgcolor=#DDAA55") + "><td width=50%><font class=find>" + FSo.item().name + "</font></td><td width=25%><font class=find>" + FSo.item().type + "</font></td><td width=50%><font class=find>" + String(FSo.item().size / (1024 * 1024)).slice(0, 3) + " MB</font></td></tr>";
                    i++
                }

            var group = FindGroup(listFiles, FSo.item().name);

            //iFrames += switcherFrames.replace(new RegExp("htmTab", "g"), htmTabName).replace(new RegExp("rtfTab", "g"), rtfTabName).replace(new RegExp("txtTab", "g"), txtTabName);

            if (FSo.item().name.slice(FSo.item().name.lastIndexOf(".")).toLowerCase() == ".bat") {

                if (group != undefined) {
                    group.batFileName = FSo.item().name;
                }
                else {
                    listFiles.push({ batFileName: FSo.item().name });
                }

                //iFrames += "<div style=\"margin-bottom: 20px;padding: 15px; background-color: #FFFFCC\"><iframe src=\"signatures\\" + FSo.item().name + "\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\"></iframe></div>";
            }

            if (FSo.item().name.slice(FSo.item().name.lastIndexOf(".")).toLowerCase() == ".htm") {

                if (group != undefined) {
                    group.htmFileName = FSo.item().name;
                }
                else {
                    listFiles.push({ htmFileName: FSo.item().name });
                }

                //iFrames += "<div style=\"margin-bottom: 20px;padding: 15px; background-color: #FFFFCC\"><iframe src=\"signatures\\" + FSo.item().name + "\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\"></iframe></div>";
            }
            //                if (FSo.item().name.slice(FSo.item().name.lastIndexOf(".")).toLowerCase() == ".rtf") {
            //                    iFrames += "<div style=\"margin-bottom: 20px\"></div><iframe src=\"signatures\\" + FSo.item().name + "\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\"></iframe>";
            //                }
            if (FSo.item().name.slice(FSo.item().name.lastIndexOf(".")).toLowerCase() == ".rtf") {

                if (group != undefined) {
                    group.rtfFileName = FSo.item().name;
                }
                else {
                    listFiles.push({ rtfFileName: FSo.item().name });
                }

                //iFrames += "<div style=\"margin-bottom: 20px;padding: 15px; background-color: #FFFFCC\"><iframe src=\"signatures\\" + FSo.item().name + "\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\"></iframe></div>";
            }

            if (FSo.item().name.slice(FSo.item().name.lastIndexOf(".")).toLowerCase() == ".txt") {

                if (group != undefined) {
                    group.txtFileName = FSo.item().name;
                }
                else {
                    listFiles.push({ txtFileName: FSo.item().name });
                }

                //iFrames += "<div style=\"margin-bottom: 20px;padding: 15px; background-color: #FFFFCC\"><iframe src=\"signatures\\" + FSo.item().name + "\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\"></iframe></div>";
            }

        }

        for (var grp in listFiles) {

            iFrames += switcherFrames.
                    replace(new RegExp("htmTab", "g"), htmTabName).
                    replace(new RegExp("rtfTab", "g"), rtfTabName).
                    replace(new RegExp("txtTab", "g"), txtTabName).
                    replace(new RegExp("frameBox", "g"), frameBox).
                    replace(new RegExp("htmFileName", "g"), listFiles[grp].htmFileName).
                    replace(new RegExp("rtfFileName", "g"), listFiles[grp].rtfFileName).
                    replace(new RegExp("txtFileName", "g"), listFiles[grp].txtFileName).
                    replace(new RegExp("batFileName", "g"), currloc + "/" + selectFolder.value + "/" + listFiles[grp].batFileName).
                    replace(new RegExp("scanSubfolder", "g"), selectFolder.value);

            var htmFile = Fo.OpenTextFile(currloc + "/" + selectFolder.value + "/" + listFiles[grp].htmFileName);
            var htmContext = htmFile.ReadAll(); 
            //iFrames += "<div style=\"margin-bottom: 20px;padding: 15px; background-color: #FFFFCC\"><iframe src=\"signatures\\" + listFiles[grp].htmFileName + "\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\"></iframe></div>";
            //iFrames += "<div style=\"margin-bottom: 20px;padding: 15px; background-color: #FFFFCC\"><iframe src=\"signatures\\" + listFiles[grp].txtFileName + "\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\"></iframe></div>";
            //iFrames += "<div style=\"margin-bottom: 20px;padding: 1px; background-color: #FFFF99\"><iframe id=\"" + frameBox + "\" src=\"" + currloc + "/" + selectFolder.value + "/" + listFiles[grp].htmFileName + "\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\"></iframe></div>";
            //iFrames += "<div style=\"margin-bottom: 20px;padding: 5px; background-color: #FFFF99\"><iframe id=\"" + frameBox + "\" src=\"\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\"></iframe></div>";

            //iFrames += "<div style=\"margin-bottom: 20px;padding: 1px; background-color: #FFFF99\"><iframe id=\"" + frameBox + "\" srcdoc=\"" + htmContext + "\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\"></iframe></div>";

            for (var i = 0; i < FieldMappings.length; i++) {
                var realValue = userinfovalues[FieldMappings[i].AdInfoField];
                if (realValue == undefined) {
                    realValue = "";
                }
                htmContext = htmContext.replace(new RegExp(FieldMappings[i].templateField, "g"), realValue); // userinfovalues[FieldMappings[i].AdInfoField]);
            }

            iFrames += "<div style=\"padding: 5px; border: thin solid #008000; margin-bottom: 20px;\"><div id=\"" + frameBox + "\" width=\"100%\" height=\"200\" frameborder=\"0\" style=\"background-color: #FFFFFF\">" + htmContext + "</div></div>";

            htmTabName += "1";
            rtfTabName += "1";
            txtTabName += "1";
            frameBox += "1";
        }
    }

    function FindGroup(list, name) {

        var fileName = name.slice(0, name.lastIndexOf(".")).toLowerCase();

        for (var grp in list) {

            if (list[grp].batFileName != undefined) {
                if (fileName == list[grp].batFileName.slice(0, list[grp].batFileName.lastIndexOf(".")).toLowerCase()) return list[grp];
            }

            if (list[grp].htmFileName != undefined) {
                if (fileName == list[grp].htmFileName.slice(0, list[grp].htmFileName.lastIndexOf(".")).toLowerCase()) return list[grp];
            }

            if (list[grp].rtfFileName != undefined) {
                if (fileName == list[grp].rtfFileName.slice(0, list[grp].rtfFileName.lastIndexOf(".")).toLowerCase()) return list[grp];
            }

            if (list[grp].txtFileName != undefined) {
                if (fileName == list[grp].txtFileName.slice(0, list[grp].txtFileName.lastIndexOf(".")).toLowerCase()) return list[grp];
            }
        }

        return undefined;
    }

    function ScanSubfolders() {
        FileName = (search.value.lastIndexOf(".") > -1) ? search.value.slice(0, search.value.lastIndexOf(".")) : (search.value.length > 0) ? search.value.toLowerCase() : "*"; //Get Searched File Name
        Extention = (search.value.lastIndexOf(".") > -1) ? search.value.slice(search.value.lastIndexOf(".") + 1).toLowerCase() : "*"; // Get Searched File Extention Name

        if (path.value.length > 0 && Fo.FolderExists(path.value)) {
            StrOut = "<table border=0 width=100% cellspacing=0>";
            iFrames = "";
            var FOo = Fo.GetFolder(path.value);

            var collSubFolders = new Enumerator(FOo.SubFolders);
            var selectInner = "";
            for (collSubFolders.moveFirst(); !collSubFolders.atEnd(); collSubFolders.moveNext()) {
                var subItem = collSubFolders.item();
                //selectInner += "<option>" + subItem.Name + "</option>";
                selectFolder.options[selectFolder.options.length] = new Option(subItem.Name, subItem.Name);
            }
            //selectFolder.innerHTML = selectInner;

            //outPut.innerHTML = StrOut + "</table>";
            outFrames.innerHTML = iFrames;

            //tableScan.style.visibility = "collapse";
        }
        else alert("Insert Correct Path Address");
    }

    function Scan() {
        FileName = (search.value.lastIndexOf(".") > -1) ? search.value.slice(0, search.value.lastIndexOf(".")) : (search.value.length > 0) ? search.value.toLowerCase() : "*"; //Get Searched File Name
        Extention = (search.value.lastIndexOf(".") > -1) ? search.value.slice(search.value.lastIndexOf(".") + 1).toLowerCase() : "*"; // Get Searched File Extention Name

        if (path.value.length > 0 && Fo.FolderExists(path.value)) {
            StrOut = "<table border=0 width=100% cellspacing=0>";
            iFrames = "";
            FindFile(Fo.GetFolder(path.value + selectFolder.value));
            //outPut.innerHTML = StrOut + "</table>";
            outFrames.innerHTML = iFrames;

            //tableScan.style.visibility = "collapse";
        }
        else alert("Insert Correct Path Address");
    }

    if (!String.prototype.trim) {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }

    var Fo = new ActiveXObject("Scripting.FileSystemObject");
    var StrOut = new String();
    var FileName = new String();
    var Extention = new String();
    var iFrames = new String();

    var switcherFrames = //"<div id=\"htmTab\" style=\"border-width: thin; border-color: #C0C0C0; border-top-style: solid; border-right-style: solid; border-left-style: solid; padding: 5px; display: inline-block; background-color: #FFFF99; width: 60px; text-align: center; cursor: pointer;\" onclick=\"EnableTab('htmTab');DisableTab('rtfTab');DisableTab('txtTab'); SetSourceForFrameBox('frameBox','scanSubfolder\\\\htmFileName');\">.htm</div>" +
    //"<div id=\"rtfTab\" style=\"border-width: thin; border-color: #C0C0C0; border-top-style: solid; border-right-style: solid; border-left-style: solid; padding: 5px; display: inline-block; background-color: #FFFFFF; width: 60px; text-align: center; cursor: pointer;\" onclick=\"EnableTab('rtfTab');DisableTab('htmTab');DisableTab('txtTab'); SetSourceForFrameBox('frameBox','scanSubfolder\\\\rtfFileName');\">.rtf</div>" +
    //"<div id=\"txtTab\" style=\"border-width: thin; border-color: #C0C0C0; border-top-style: solid; border-right-style: solid; border-left-style: solid; padding: 5px; display: inline-block; background-color: #FFFFFF; width: 60px; text-align: center; cursor: pointer;\" onclick=\"EnableTab('txtTab');DisableTab('rtfTab');DisableTab('htmTab'); SetSourceForFrameBox('frameBox','scanSubfolder\\\\txtFileName');\">.txt</div>" +

    //"<div style=\"padding: 5px; margin: 5px; display: inline-block; background-color: #99FF66; width: 160px; text-align: right; cursor: pointer; float: right;\"><a style=\"font-weight: bold; text-decoration: none;\" href=\"scanSubfolder/batFileName\">batFileName</a></div>";
    "<div style=\"padding: 5px; margin: 5px; display: inline-block; background-color: #99FF66; text-align: right; cursor: pointer; float: right;\"><a style=\"font-weight: bold; text-decoration: none;\" href=\"file:///scanSubfolder/batFileName\">batFileName</a></div>";

    var myloc = window.location.href;
    var locarray = myloc.split("/");
    delete locarray[(locarray.length - 1)];
    delete locarray[0];
    delete locarray[0];
    delete locarray[0];
    //var currloc = locarray.join("/").slice(3);//  + "signatures";
    //var currloc = "\\\\HOME91DOMAIN\\adolsign-2.1-aon\\"; //  locarray.join("/").slice(3);//  + "signatures";
    //var currloc = "Z:\\"; //  locarray.join("/").slice(3);//  + "signatures";
    var currloc = PathToTemplates;
    //path.value = currloc;
    
    var path = new Object();
    path.value = currloc;

    var search = new Object();
    search.value = '';

    var isFieldMappings = false;
    var FieldMappings = new Array();
     
    var adolsignConfigFile = Fo.OpenTextFile(PathToAdolsignConfig);
    while (!adolsignConfigFile.AtEndOfStream) {
        var lineConfig = adolsignConfigFile.ReadLine().trim();
        if (lineConfig[0] != "#") {
            if (lineConfig[0] == "[") {
                if (lineConfig.toLowerCase() == "[field mappings]") {
                    isFieldMappings = true;
                }
                else {
                    isFieldMappings = false;
                }
            }
            else {
                if (isFieldMappings) {
                    lineConfig = lineConfig.replace(new RegExp("\\s+", "g"), "").toLowerCase();
                    var eqPos = lineConfig.indexOf("=");
                    if (eqPos != -1) {
                        var mapping = new Object();
                        mapping.templateField = lineConfig.slice(0, eqPos);
                        mapping.AdInfoField = lineConfig.slice(eqPos + 1);
                        FieldMappings.push(mapping);// = ; //, -1);
                    }
                }
            }
        }
    }
    //var adolsignConfigContent = adolsignConfigFile.ReadAll();
    //adolsignConfigContent.

    //ScanSubfolders();
    selectFolder.options[selectFolder.options.length] = new Option('.', '.');
    Scan();

</script>

</html>
